package com.kgc.storeprovider.service.impl;

import com.github.pagehelper.PageHelper;
import com.kgc.basic.pojo.Good;
import com.kgc.basic.util.PageInfo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.store.pojo.*;
import com.kgc.storeprovider.dao.*;
import com.kgc.storeprovider.feign.SalesCounterFeign;
import com.kgc.storeprovider.service.ProMoveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class ProMoveServiceImpl  implements ProMoveService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProMoveMapper proMoveMapper;
    @Autowired
    private SalesCounterFeign salesCounterFeign;
    @Autowired
    private StoreGoodSummaryMapper storeGoodSummaryMapper;
    @Autowired
    private OutStoreMapper outStoreMapper;
    @Autowired
    private OutStoreDetailMapper outStoreDetailMapper;
    @Autowired
    private InStoreMapper inStoreMapper;
    @Autowired
    private InStoreDetailMapper inStoreDetailMapper;
    @Override
    public ResponseMsg selectByPage(Map<String, Object> map) {
        logger.info("ProMoveServiceImpl selectByPage map={}", map);
        ResponseMsg responseMsg = new ResponseMsg();
        PageHelper.startPage(Integer.parseInt(map.get("pageNow").toString()), Integer.parseInt(map.get("pageSize").toString()));
        List<ProMove> list = proMoveMapper.getAllProMove(map);
        logger.debug("proMoveMapper getAllProMove list:{}", list+",map"+map);
        PageHelper.clearPage();
        PageInfo<ProMove> pageInfo = new PageInfo<>();
        if(list!=null&& !list.isEmpty()){
            pageInfo.setList(list);
            pageInfo.setPageNo(Integer.parseInt(map.get("pageNow").toString()));
            pageInfo.setPageSize(Integer.parseInt(map.get("pageSize").toString()));
            pageInfo.setTotal(proMoveMapper.getProMoveCount(map));
            logger.debug("proMoveMapper getProMoveCount count:"+pageInfo.getTotal()+",map"+map);
        }
        if(pageInfo.getList()!=null&&pageInfo.getList().size()>0){
            responseMsg.setCode("200");
            responseMsg.setData(pageInfo);
        }else {
            responseMsg.setCode("201");
        }
        return responseMsg;
    }

    @Override
    public ResponseMsg selectByCode(String code) {
        logger.info("ProMoveServiceImpl selectByCode code={}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        ProMove proMove = proMoveMapper.selectByCode(code);
        logger.debug("proMoveMapper selectByCode proMove:{}", proMove+",code"+code);
        if(proMove!=null){
            responseMsg.setCode("200");
            responseMsg.setData(proMove);
        }else {
            responseMsg.setCode("201");
        }
        return responseMsg;
    }

    @Override
    public ResponseMsg update(ProMove proMove) {
        logger.info("ProMoveServiceImpl update proMove={}", proMove);
        ResponseMsg responseMsg = new ResponseMsg();
        proMove.setUpdateDate(new Date());
//        proMove.setUpdateUser("admin");
        int count = proMoveMapper.updateProMove(proMove);
        logger.debug("proMoveMapper updateProMove:{}", proMove+",count:"+count);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code",proMove.getCode());
        count = proMoveMapper.delDetail(map);
        logger.debug("proMoveMapper updateProMove:{}", proMove+",count:"+count);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        map.put("createUser",proMove.getCreateUser());
        map.put("createDate",proMove.getCreateDate());
        map.put("updateUser",proMove.getUpdateUser());
        map.put("updateDate",proMove.getUpdateDate());
        List<Good> list = proMove.getGoods();
        List<Integer> numList = proMove.getCounts();
        List<Integer> isids = proMove.getIsids();
        List<Integer> osids = proMove.getOsids();
        for (int i=0;i<list.size();i++){
            Good good = list.get(i);
            map.put("gid",good.getId());
            int num = numList.get(i);
            int isid = isids.get(i);
            int osid = osids.get(i);
            map.put("count",num);
            map.put("isid",isid);
            map.put("osid",osid);
            int nu = proMoveMapper.addDetail(map);
            logger.debug("costAdjustmentMapper addDetail nu:{}",nu+",map"+map);
            if(num==0){
                responseMsg.setCode("201");
                return responseMsg;
            }
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg add(ProMove proMove) {
        logger.info("CostAdjustmentServiceImpl add proMove:{}", proMove);
        proMove.setStatus(1);
        proMove.setCreateDate(new Date());
//        proMove.setCreateUser("admin");
        proMove.setUpdateDate(new Date());
//        proMove.setUpdateUser("admin");
        ResponseMsg responseMsg = new ResponseMsg();
        int count = proMoveMapper.addProMove(proMove);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code",proMove.getCode());
        List<Good> list = proMove.getGoods();
        List<Integer> numList = proMove.getCounts();
        List<Integer> isids = proMove.getIsids();
        List<Integer> osids = proMove.getOsids();
        map.put("createUser",proMove.getCreateUser());
        map.put("createDate",proMove.getCreateDate());
        map.put("updateUser",proMove.getUpdateUser());
        map.put("updateDate",proMove.getUpdateDate());
        for (int i=0;i<list.size();i++){
            Good good = list.get(i);
            map.put("gid",good.getId());
            int num = numList.get(i);
            int isid = isids.get(i);
            int osid = osids.get(i);
            map.put("count",num);
            map.put("isid",isid);
            map.put("osid",osid);
            int nu = proMoveMapper.addDetail(map);
            logger.debug("costAdjustmentMapper addDetail nu:{}",nu+",map"+map);
            if(num==0){
                responseMsg.setCode("201");
                return responseMsg;
            }
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg del(String code) {
        logger.info("ProMoveServiceImpl del code:{}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        int count = proMoveMapper.delProMove(code);
        logger.debug("proMoveMapper delProMove count:{}", count+",code"+code);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        count = proMoveMapper.deleteDetail(code);
        logger.debug("proMoveMapper deleteDetail count:{}", count+",code"+code);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg changeStatus(String code, String status) {
        logger.info("ProMoveServiceImpl step code:{}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        int count = proMoveMapper.changeStatus(code,status);
        logger.debug("proMoveMapper changeStatus count:{}", count+",code"+code);
        if(count>0){
            responseMsg.setCode("200");
        }else {
            responseMsg.setCode("201");
        }
        return responseMsg;
    }
    // 1. 调拨单转出库单
    @Override
    public OutStore createOutStoreFromProMove(ProMove move) {
        OutStore out = new OutStore();
        // 1.1 生成出库单号
        Map<String, Object> map = new HashMap<>();
        map.put("docType", "DBCK"); // 调拨出库
        String code = salesCounterFeign.addSalesCode(map).getData().toString();
        out.setCode(code);

        // 1.2 填充出库主表
        out.setOrderDate(move.getDate());
        out.setSourceCode(move.getCode());     // 来源调拨单号
        out.setCid((int)move.getSkid());       // 客户/组织 暂复用 skid
        out.setDeptId((int)move.getSkid());    // 部门ID 可以自定义
        out.setStoreManId((int)move.getSkid());// 仓管员ID 也可根据业务调整
        out.setTypeId(move.getTypeId());
        out.setOrderTypeId(move.getTypeId());
        out.setIsDelete(0);
        out.setCreateId( (int)move.getCreateUser().hashCode() ); // 示例
        out.setCreateName(move.getCreateUser());
        out.setCreateDate(new Date());

        // 1.3 明细：按 goods & osids
        List<OutStoreDetail> details = new ArrayList<>();
        List<Good>  goods  = move.getGoods();
        List<Integer> counts = move.getCounts();
        List<Integer> osids = move.getOsids();
        for (int i = 0; i < goods.size(); i++) {
            Good g = goods.get(i);
            OutStoreDetail d = new OutStoreDetail();
            d.setOutStoreCode(code);
            d.setGoodId((int)g.getId());
            d.setGoodsCode(g.getCode());
            d.setGoodsName(g.getName());
            d.setCount(counts.get(i));
            d.setStoreId(osids.get(i));            // 出库仓库
            d.setStoreName(move.getSkname());       // 如需对应名称列表，可自行改

            BigDecimal price = storeGoodSummaryMapper
                    .selectKcStoreGoodBySidCid(d.getStoreId(), d.getGoodId())
                    .getPrice();
            d.setPrice(price);
            d.setSumPrice(price.multiply(BigDecimal.valueOf(d.getCount())));

            d.setCreateId((int)move.getCreateUser().hashCode());
            d.setCreateName(move.getCreateUser());
            d.setCreateDate(new Date());
            details.add(d);
        }

        // 1.4 保存
        saveOutStore(out, details);
        return out;
    }

    private void saveOutStore(OutStore out, List<OutStoreDetail> details) {
        if (outStoreMapper.insertOutStore(out) <= 0) {
            throw new RuntimeException("调拨出库单保存失败");
        }
        for (OutStoreDetail d : details) {
            d.setOutStoreCode(out.getCode());
            if (outStoreDetailMapper.insertOutStoreDetail(d) <= 0) {
                throw new RuntimeException("调拨出库明细保存失败");
            }
        }
    }

    // 2. 调拨单转入库单
    @Override
    public InStore createInStoreFromProMove(ProMove move) {
        InStore in = new InStore();
        // 2.1 生成入库单号
        Map<String, Object> map = new HashMap<>();
        map.put("docType", "DBRK"); // 调拨入库
        String code = salesCounterFeign.addSalesCode(map).getData().toString();
        in.setCode(code);

        // 2.2 填充入库主表
        in.setOrderDate(move.getDate());
        in.setSourceCode(move.getCode());
        in.setPid((int)move.getSkid());
        in.setDeptId((int)move.getSkid());
        in.setStoreManId((int)move.getSkid());
        in.setTypeId(move.getTypeId());
        in.setOrderTypeId(move.getTypeId());
        in.setIsDelete(0);
        in.setCreateId((int)move.getCreateUser().hashCode());
        in.setCreateName(move.getCreateUser());
        in.setCreateDate(new Date());

        // 2.3 明细：按 goods & isids
        List<InStoreDetail> details = new ArrayList<>();
        List<Good>  goods  = move.getGoods();
        List<Integer> counts = move.getCounts();
        List<Integer> isids = move.getIsids();
        for (int i = 0; i < goods.size(); i++) {
            Good g = goods.get(i);
            InStoreDetail d = new InStoreDetail();
            d.setInStoreCode(code);
            d.setGoodId((int)g.getId());
            d.setGoodsCode(g.getCode());
            d.setGoodsName(g.getName());
            d.setCount(counts.get(i));
            d.setStoreId(isids.get(i));           // 入库仓库
            d.setStoreName(move.getSkname());

            BigDecimal price = storeGoodSummaryMapper
                    .selectKcStoreGoodBySidCid(d.getStoreId(), d.getGoodId())
                    .getPrice();
            d.setPrice(price);
            d.setSumPrice(price.multiply(BigDecimal.valueOf(d.getCount())));

            d.setCreateId((int)move.getCreateUser().hashCode());
            d.setCreateName(move.getCreateUser());
            d.setCreateDate(new Date());
            details.add(d);
        }

        // 2.4 保存
        saveInStore(in, details);
        return in;
    }

    private void saveInStore(InStore in, List<InStoreDetail> details) {
        if (inStoreMapper.insertInStore(in) <= 0) {
            throw new RuntimeException("调拨入库单保存失败");
        }
        for (InStoreDetail d : details) {
            d.setInStoreCode(in.getCode());
            if (inStoreDetailMapper.insertInStoreDetail(d) <= 0) {
                throw new RuntimeException("调拨入库明细保存失败");
            }
        }
    }
}
